import requests
import logging
import time


def push_msg(message: str, push_url: str, push_headers: dict, push_token: str,
             push_qq: int, push_target: list, push_delay: int):
    try:
        verify_url = push_url + '/verify'
        verify_data = {"verifyKey": push_token}
        verify_response_data = requests.post(url=verify_url, json=verify_data)
        if (verify_response_data.json()['code'] == 0):
            bind_url = push_url + '/bind'
            bind_data = {
                "sessionKey": verify_response_data.json()['session'],
                "qq": push_qq
            }
            bind_response_data = requests.post(url=bind_url, json=bind_data)
            if (bind_response_data.json()['code'] == 0):
                group_message_url = push_url + '/sendGroupMessage'
                group_message_data = {
                    "sessionKey": verify_response_data.json()['session'],
                    "target": None,
                    "messageChain": [{
                        "type": "Plain",
                        "text": "test"
                    }]
                }
                group_message_data['messageChain'][0]['text'] = message
                for target in push_target:
                    group_message_data['target'] = target
                    group_message_response_data = requests.post(
                        url=group_message_url,
                        json=group_message_data,
                        headers=push_headers)
                    if (group_message_response_data.json()['code'] == 0):
                        logging.info(f'推送成功，推送目标：{str(target)}')
                    else:
                        logging.error(
                            f'推送失败，推送目标：{str(target)} ，返回内容：{str(group_message_response_data.json())}'
                        )
                    time.sleep(push_delay)
                release_url = push_url + '/release'
                release_data = {
                    "sessionKey": verify_response_data.json()['session'],
                    "qq": push_qq
                }
                release_response_data = requests.post(url=release_url,
                                                      json=release_data)
                if (release_response_data.json()['code'] != 0):
                    logging.warning(f'释放失败，{str(verify_response_data.json())}')
                else:
                    logging.info(f'qq推送成功')
            else:
                logging.warning(f'绑定失败，{str(bind_response_data.json())}')
        else:
            logging.warning(
                f'sessionKey获取失败，{str(verify_response_data.json())}')
    except Exception as e:
        logging.warning(e, f'位置{str(e.__traceback__.tb_lineno)}')
